package com.yoomiito.app.widget;

import android.content.Context;
import androidx.appcompat.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.Button;

import cn.droidlover.xdroidmvp.log.XLog;

public class MyEditText extends AppCompatEditText implements TextWatcher {


    private int mLength;

    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    private Button mButton;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        XLog.d("YM","afterTextChanged");
        String str = s.toString();
        mLength = str.length();
        if (mLength < 4) {

            return;
        }
        switch (number) {
            case 4:
                if (mLength == 4) {
                    setButtonState(true);
                } else {
                    setButtonState(false);
                }
                break;
            case 6:
                if (mLength == 6) {
                    setButtonState(true);
                } else {
                    setButtonState(false);
                }
                break;
            case 11:
                if (mLength == 11) {
                    if (mOnClearStateListener != null) {
                        mOnClearStateListener.onShow();
                    }
                    setButtonState(true);
                } else {
                    setButtonState(false);
                    if (mOnClearStateListener != null) {
                        mOnClearStateListener.onHide();
                    }
                }
                break;
        }
    }


    private void setButtonState(boolean isEnabled) {
        if (isEnabled) {
            mButton.setEnabled(true);
        } else {
            mButton.setEnabled(false);
        }
    }

    private int number;

    public MyEditText setNumber(int number) {
        this.number = number;
        return this;
    }


    public MyEditText setButton(Button bundle) {
        mButton = bundle;
        return this;
    }

    public void removTextWatcher() {
        removeTextChangedListener(this);
    }


    public void setOnClearLisenter(mOnClearStateListener mOnClearStateListener) {
        this.mOnClearStateListener = mOnClearStateListener;
    }

    mOnClearStateListener mOnClearStateListener;

    public interface mOnClearStateListener {

        void onShow();

        void onHide();
    }
}
